import { Toast } from 'react-vant';
/**
 * 异步防抖函数
 */
function debounceAsync(fn: Function, wait = 1000) {
  let timeoutId: any | null = null;
  let lastReject: Function | null = null;

  return function (this: Function, ...args: any[]) {
    // 如果存在之前的定时器，清除并拒绝之前的 Promise
    if (timeoutId) {
      clearTimeout(timeoutId);
      lastReject?.(new Error('Debounced function canceled'));
    }

    // 返回新的 Promise
    return new Promise((resolve, reject) => {
      // 保存当前 reject 方法
      lastReject = reject;

      // 设置新的定时器
      timeoutId = setTimeout(async () => {
        try {
          // 执行异步函数并等待结果
          const result = await fn.apply(this, args);
          resolve(result);
        } catch (err) {
          reject(err);
        } finally {
          // 清理状态
          timeoutId = null;
          lastReject = null;
        }
      }, wait);
    });
  };
}

/**
 * 如果在数据不为空时对数据进行处理，否则返回"-"。
 * 返回处理后的数据。
 */
const hb = (obj: any, callback = (d: any) => d): any => {
  if (obj == null || obj === '') return '-';
  return callback(obj);
};

/**
 * 接受请求结果(promise)并处理,消息(静默成功)，加载状态，成功后的绑定
 */
const promptResult = async (
  promise: Promise<ResponseApiDto>,
  setLoading: Function = () => {},
  bind: Function = () => {},
  failMsg = '失败了'
) => {
  setLoading(true);
  const res = await promise;
  if (res.status >= 0) {
    // Notify.show({ type: "success", message: successMsg });
    bind(); // 不必等待
  } else {
    Toast.fail(failMsg);
  }
  setLoading(false);
  return res;
};

const stringIsSame = (str1: string, str2: string, ignore: boolean = false) => {
  if (ignore) return str1.toLowerCase() === str2.toLowerCase();
  else return str1 === str2;
};

const stringStartWith = (str1: string, str2: string, ignore: boolean = false) => {
  if (ignore) return str1.toLowerCase().startsWith(str2.toLowerCase());
  else return str1.startsWith(str2);
};

const recursion = (
  trees: any,
  childrenName: string,
  callBack: (tree: any, parent: any) => void,
  parent = null
) => {
  for (let i = 0; i < trees.length; i++) {
    const tree = trees[i];
    callBack(tree, parent);
    if (tree[childrenName]) {
      recursion(tree[childrenName], childrenName, callBack, tree);
    }
  }
};

// 递归匹配函数
/**
 * 根据 path 匹配路由对象
 * @param path 要匹配的路径
 * @param routes 路由配置数组
 * @returns 匹配到的路由对象或 undefined
 */
function matchRoute(path: string, routes: any[]): any | undefined {
  // 标准化路径，移除开头和结尾的斜杠
  const normalizedPath = path.replace(/^\/|\/$/g, '');
  const pathSegments = normalizedPath.split('/').filter(Boolean);

  // 递归匹配函数
  function match(segments: string[], routeObjects: any[]): any | undefined {
    for (const route of routeObjects) {
      // 情况1：当前路由是索引路由，且没有剩余路径段
      if (route.index && segments.length === 0) {
        return route;
      }

      // 情况2：当前路由有 path 属性
      if (route.path) {
        const routePath = route.path.replace(/^\/|\/$/g, '');
        const routeSegments = routePath.split('/').filter(Boolean);

        // 检查是否完全匹配当前路由路径
        if (segments.length === routeSegments.length) {
          let isMatch = true;
          for (let i = 0; i < segments.length; i++) {
            if (!routeSegments[i].startsWith(':') && routeSegments[i] !== segments[i]) {
              isMatch = false;
              break;
            }
          }
          if (isMatch) {
            // 如果是完全匹配，检查是否有索引子路由
            if (route.children) {
              const indexChild = route.children.find((child: any) => child.index);
              if (indexChild && segments.length === routeSegments.length) {
                return indexChild;
              }
            }
            return route;
          }
        }

        // 检查是否是部分匹配（可能有嵌套路由）
        if (route.children && routeSegments.length <= segments.length) {
          let isPartialMatch = true;
          for (let i = 0; i < routeSegments.length; i++) {
            if (!routeSegments[i].startsWith(':') && routeSegments[i] !== segments[i]) {
              isPartialMatch = false;
              break;
            }
          }

          if (isPartialMatch) {
            const remainingSegments = segments.slice(routeSegments.length);
            // 如果没有剩余路径段，尝试返回索引路由
            if (remainingSegments.length === 0) {
              const indexChild = route.children.find((child: any) => child.index);
              if (indexChild) {
                return indexChild;
              }
            }
            const matchedChild = match(remainingSegments, route.children);
            if (matchedChild) {
              return matchedChild;
            }
          }
        }
      }

      // 情况3：当前路由没有 path 但有 children（如布局路由）
      if (!route.path && route.children) {
        const matchedChild = match(segments, route.children);
        if (matchedChild) {
          return matchedChild;
        }
      }
    }

    return undefined;
  }

  // 特殊处理根路径 '/'
  if (path === '/') {
    // 查找根路径下的索引路由
    for (const route of routes) {
      if ((!route.path || route.path === '/') && route.children) {
        const indexRoute = route.children.find((child: any) => child.index);
        if (indexRoute) {
          return indexRoute;
        }
      }
    }
  }

  return match(pathSegments, routes);
}

// 使用示例
// const matchedRoute = matchRoute('/good/detail/123', routes);
// console.log(matchedRoute); // 将返回 GoodDetail 路由对象

const getBusinessImagePath = (id: number, imageName: string) => {
  return import.meta.env.VITE_BASE_URL + '/Images/Business/' + id + '/' + imageName;
};
const getGoodsImagePath = (id: number, imageName: string) => {
  return import.meta.env.VITE_BASE_URL + '/Images/Goods/' + id + '/' + imageName;
};
const getSuppliersImagePath = (id: number, imageName: string) => {
  return import.meta.env.VITE_BASE_URL + '/Images/Supplier/' + id + '/' + imageName;
};

const getDefaultAvatarPath = () => {
  return import.meta.env.VITE_BASE_URL + '/Images/Default/default_tx.jpg';
};

const getSaleCount = (saleCout: number): string => {
  if (saleCout < 100) {
    return saleCout + '';
  } else if (saleCout < 200) {
    return '99+';
  } else if (saleCout < 1000) {
    return saleCout + '';
  } else if (saleCout < 2000) {
    return '999+';
  } else if (saleCout < 10000) {
    return Math.floor(saleCout / 1000) + 'k';
  } else {
    return Math.floor(saleCout / 10000) + '万';
  }
};

/**
 * 如果传入的对象不为空返回回调函数的返回值，否则返回空
 * @param obj
 * @param callBack
 * @returns
 */
const sn = (obj: any | void, callBack?: (obj: any) => any): any => {
  if (obj != null) {
    if (callBack) {
      return callBack(obj);
    } else {
      return obj;
    }
  }
};

export {
  debounceAsync,
  hb,
  sn,
  stringIsSame,
  stringStartWith,
  promptResult,
  getBusinessImagePath,
  getGoodsImagePath,
  getSuppliersImagePath,
  getDefaultAvatarPath,
  recursion,
  matchRoute,
  getSaleCount,
};
